package org.jeecg.modules.enterpriseBasicInformation.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.enterpriseBasicInformation.entity.EnterpriseBasicInformation;
import org.jeecg.modules.enterpriseBasicInformation.service.IEnterpriseBasicInformationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 企业基本信息
 * @Author: jeecg-boot
 * @Date: 2024-02-05
 * @Version: V1.0
 */
@Api(tags = "企业基本信息")
@RestController
@RequestMapping("/enterpriseBasicInformation/enterpriseBasicInformation")
@Slf4j
public class EnterpriseBasicInformationController extends JeecgController<EnterpriseBasicInformation, IEnterpriseBasicInformationService> {
    @Autowired
    private IEnterpriseBasicInformationService enterpriseBasicInformationService;
    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 分页列表查询
     *
     * @param enterpriseBasicInformation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "企业基本信息-分页列表查询")
    @ApiOperation(value = "企业基本信息-分页列表查询", notes = "企业基本信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(EnterpriseBasicInformation enterpriseBasicInformation,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<EnterpriseBasicInformation> queryWrapper = QueryGenerator.initQueryWrapper(enterpriseBasicInformation, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser.getRealname();
        if(!username.equals("admin")) {
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if (departNames == null || departNames.size() == 0) {
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("enterprise_name", departNames.get(0));
        }
        Page<EnterpriseBasicInformation> page = new Page<EnterpriseBasicInformation>(pageNo, pageSize);
        IPage<EnterpriseBasicInformation> pageList = enterpriseBasicInformationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "企业基本信息-企业信息查询")
    @ApiOperation(value = "企业基本信息-企业信息查询", notes = "企业基本信息-企业信息查询")
    @GetMapping(value = "/company")
    public Result<?> queryCompany() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
        List<String> departNames = sysDeparts.stream()
                .filter(item -> item.getOrgType().equals("1"))
                .map(SysDepart::getDepartName)
                .collect(Collectors.toList());
        if (departNames == null || departNames.size() == 0) {
            return Result.error("未找到公司信息，请联系管理员");
        }
        LambdaQueryWrapper<EnterpriseBasicInformation> queryWrapper = Wrappers.lambdaQuery(EnterpriseBasicInformation.class);
        queryWrapper.eq(EnterpriseBasicInformation::getEnterpriseName, departNames.get(0));
        EnterpriseBasicInformation one = enterpriseBasicInformationService.getOne(queryWrapper);
        if (Objects.isNull(one)){
            one = new EnterpriseBasicInformation();
            one.setCreateBy(departNames.get(0));
            one.setCreateTime(new Date());
            one.setEnterpriseName(departNames.get(0));
            enterpriseBasicInformationService.save(one);
        }
        return Result.OK(one);
    }

    /**
	 * 企业名称查询
     * @return
     */
    @AutoLog(value = "企业基本信息-企业名称查询")
    @ApiOperation(value = "企业基本信息-企业名称查询", notes = "企业基本信息-企业名称查询")
    @GetMapping(value = "/getEnterpriseName")
    public Result<?> queryPageList() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
        List<String> departNames = sysDeparts.stream()
                .filter(item -> item.getOrgType().equals("1"))
                .map(SysDepart::getDepartName)
                .collect(Collectors.toList());
        if (departNames == null || departNames.size() == 0) {
            return Result.error("未找到公司信息，请联系管理员");
        }
        LambdaQueryWrapper<EnterpriseBasicInformation> lqw = Wrappers.lambdaQuery(EnterpriseBasicInformation.class);
        lqw.eq(EnterpriseBasicInformation::getEnterpriseName, departNames.get(0));
        lqw.orderByDesc(EnterpriseBasicInformation::getCreateTime);
        List<EnterpriseBasicInformation> list = enterpriseBasicInformationService.list(lqw);
		EnterpriseBasicInformation enterpriseBasicInformation = list.get(0);
		return Result.OK(enterpriseBasicInformation.getEnterpriseName());
    }

    /**
     * 企业名称查询
     * @return
     */
    @AutoLog(value = "企业基本信息-对外-企业名称集合查询")
    @ApiOperation(value = "企业基本信息-对外-企业名称集合查询", notes = "企业基本信息-对外-企业名称集合查询")
    @GetMapping(value = "/getEnterpriseNames")
    public Result<?> queryPageLists() {
        List<EnterpriseBasicInformation> list = enterpriseBasicInformationService.list();
        List<String> collect = list.stream().map(item -> item.getEnterpriseName()).collect(Collectors.toList());
        return Result.OK(collect);
    }

    /**
     * 添加
     *
     * @param enterpriseBasicInformation
     * @return
     */
    @AutoLog(value = "企业基本信息-添加")
    @ApiOperation(value = "企业基本信息-添加", notes = "企业基本信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EnterpriseBasicInformation enterpriseBasicInformation) {
        enterpriseBasicInformationService.save(enterpriseBasicInformation);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param enterpriseBasicInformation
     * @return
     */
    @AutoLog(value = "企业基本信息-编辑")
    @ApiOperation(value = "企业基本信息-编辑", notes = "企业基本信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody EnterpriseBasicInformation enterpriseBasicInformation) {
        enterpriseBasicInformationService.updateById(enterpriseBasicInformation);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "企业基本信息-通过id删除")
    @ApiOperation(value = "企业基本信息-通过id删除", notes = "企业基本信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        enterpriseBasicInformationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "企业基本信息-批量删除")
    @ApiOperation(value = "企业基本信息-批量删除", notes = "企业基本信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.enterpriseBasicInformationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "企业基本信息-通过id查询")
    @ApiOperation(value = "企业基本信息-通过id查询", notes = "企业基本信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        EnterpriseBasicInformation enterpriseBasicInformation = enterpriseBasicInformationService.getById(id);
        if (enterpriseBasicInformation == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(enterpriseBasicInformation);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param enterpriseBasicInformation
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EnterpriseBasicInformation enterpriseBasicInformation) {
        return super.exportXls(request, enterpriseBasicInformation, EnterpriseBasicInformation.class, "企业基本信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EnterpriseBasicInformation.class);
    }

}
